package com.dtjd.playcoinmonkey.activities.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;
import androidx.core.content.res.ResourcesCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.dtjd.playcoinmonkey.BuildConfig;
import com.dtjd.playcoinmonkey.MyApplication;
import com.dtjd.playcoinmonkey.R;
import com.dtjd.playcoinmonkey.bean.HttpParaBean;
import com.dtjd.playcoinmonkey.databinding.ActivityMainBinding;
import com.dtjd.playcoinmonkey.databinding.DialogDownBinding;
import com.dtjd.playcoinmonkey.utils.Network;
import com.dtjd.playcoinmonkey.utils.Tools;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
    @SuppressLint("StringFormatInvalid")
    @RequiresApi(api = Build.VERSION_CODES.R)
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        AppBarConfiguration appBarConfiguration;
        if (MyApplication.needTicket){
             appBarConfiguration = new AppBarConfiguration.Builder(R.id.navigation_home, R.id.navigation_recommend,R.id.navigation_ticket, R.id.navigation_me).build();
        }else {
            appBarConfiguration = new AppBarConfiguration.Builder(R.id.navigation_home, R.id.navigation_recommend, R.id.navigation_me).build();
        }
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(binding.navView, navController);
        if (MyApplication.needTicket){
            binding.navView.inflateMenu(R.menu.bottom_nav_menu_ticket);
        }else {
            binding.navView.inflateMenu(R.menu.bottom_nav_menu);
        }
        ActionBar actionbar = getSupportActionBar();
        if (actionbar!=null)actionbar.hide();
        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,Manifest.permission.MANAGE_EXTERNAL_STORAGE}, 0);
        TTAdSdk.getAdManager().requestPermissionIfNecessary(this);
        Network.post(new ArrayList<>(), "wbhMain/getVersion", new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                runOnUiThread(() -> {
                    try {
                        JSONObject jo = new JSONObject(Objects.requireNonNull(response.body()).string()).getJSONObject("datalist");

                       String url= jo.getString("url");

                        if (jo.getString("forcedUpdate").equals("1")&&jo.getInt("version")>getPackageManager().getPackageInfo(getPackageName(),0).versionCode){
                            BottomSheetDialog dialog = new BottomSheetDialog(MainActivity.this);
                            @SuppressLint("InflateParams") View commentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog,null);
                            ((TextView)commentView.findViewById(R.id.dialog_title)).setText(getString(R.string.newVersionFOund));
                            ((TextView)commentView.findViewById(R.id.dialog_content)).setText(getString(R.string.newVersionIs,jo.getString("versionName")));
                            TextView left=commentView.findViewById(R.id.dialog_button_left);
                            TextView right=commentView.findViewById(R.id.dialog_button_right);
                            left.setText(getResources().getString(R.string.update));
                            right.setText(getResources().getString(R.string.exit));
                            left.setOnClickListener(view->{
                                downloadNewVersion(url);
                                dialog.dismiss();
                            });
                            right.setOnClickListener(view-> finish());
                            dialog.setCancelable(false);
                            dialog.setContentView(commentView);
                            dialog.show();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
        if (MyApplication.wb_money>0){
            Tools.showDialog2(this, getResources().getString(R.string.tips), getResources().getString(R.string.restm2,String.valueOf(MyApplication.wb_money)), getResources().getString(R.string.extract),getResources().getString(R.string.extractTips), (o, dialog) -> {
                dialog.dismiss();
                List<HttpParaBean>para=new ArrayList<>();
                para.add(new HttpParaBean("totalPrice",String.valueOf(MyApplication.wb_money)));
                para.add(new HttpParaBean("token","token"));
                Network.post(para, "wbh/withdraw", new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) {
                        runOnUiThread(()->{
                            try {
                                Tools.toast(new JSONObject(Objects.requireNonNull(response.body()).string()).getString("datalist"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }
                });
            });
        }
        TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(this);
        AdSlot adSlot = new AdSlot.Builder().setCodeId("947077923").setExpressViewAcceptedSize(500,500).setSupportDeepLink(true).setOrientation(TTAdConstant.VERTICAL).build();
        mTTAdNative.loadFullScreenVideoAd(adSlot, new TTAdNative.FullScreenVideoAdListener() {
            @Override
            public void onError(int i, String s) { }
            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ttFullScreenVideoAd) {
                ttFullScreenVideoAd.showFullScreenVideoAd(MainActivity.this, TTAdConstant.RitScenes.GAME_GIFT_BONUS, null);
            }
            @Override
            public void onFullScreenVideoCached() { }
            @Override
            public void onFullScreenVideoCached(TTFullScreenVideoAd ttFullScreenVideoAd) { }
        });
    }
    @SuppressLint("SdCardPath")
    private void downloadNewVersion(String url) {
        @NonNull DialogDownBinding downloadBinding = DialogDownBinding.inflate(getLayoutInflater());
        AlertDialog dialog1=new AlertDialog.Builder(this).setView(downloadBinding.getRoot()).setCancelable(false).show();
        WindowManager.LayoutParams p = dialog1.getWindow().getAttributes();
        p.width = ((int)(getWindowManager().getDefaultDisplay().getWidth() * 0.8));
        dialog1.getWindow().setAttributes(p);
        dialog1.getWindow().setBackgroundDrawable(ResourcesCompat.getDrawable(getResources(),R.drawable.dialogbg,null));
        dialog1.setView(downloadBinding.getRoot());
        dialog1.show();


        FileDownloader.setup(this);
        FileDownloader.getImpl().create(url).setPath(FileDownloadUtils.getDefaultSaveRootPath()+File.separator+"1.apk").setListener(new FileDownloadListener() {
            @SuppressLint("SetTextI18n")
            @Override
            protected void pending(BaseDownloadTask task, int progress, int totalBytes) {
                downloadBinding.progressbar.setMax(totalBytes);
                downloadBinding.progressbar.setProgress(progress);
                downloadBinding.text.setText("Pending...");
            }
            @SuppressLint("SetTextI18n")
            @Override
            protected void connected(BaseDownloadTask task, String tag, boolean isContinue, int progress, int totalBytes) {
                downloadBinding.progressbar.setMax(totalBytes);
                downloadBinding.progressbar.setProgress(progress);
                downloadBinding.text.setText("Pending...");
            }

            @Override
            protected void progress(BaseDownloadTask task, int progress, int totalBytes){
                downloadBinding.progressbar.setMax(totalBytes);
                downloadBinding.progressbar.setProgress(progress);
                downloadBinding.text.setText(Tools.getPercent(progress,totalBytes));

            }
            @Override
            protected void blockComplete(BaseDownloadTask task) {
            }
            @Override
            protected void retry(final BaseDownloadTask errortask, final Throwable ex, final int retryingTimes, final int progress) {
                downloadBinding.progressbar.setProgress(progress);
                downloadBinding.text.setText("正在重试");
            }
            @Override
            protected void completed(BaseDownloadTask task) {
                downloadBinding.text.setText("正在安装");
                File file = new File(FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "1.apk");
                Intent intent = new Intent(Intent.ACTION_VIEW);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".FileProvider", file);
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                } else {
                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }
                startActivity(intent);
            }
            @Override
            protected void paused(BaseDownloadTask task, int progress, int totalBytes) {
                downloadBinding.progressbar.setMax(totalBytes);
                downloadBinding.progressbar.setProgress(progress);
                downloadBinding.text.setText(Tools.getPercent(progress,totalBytes));
            }
            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                e.printStackTrace();
            }
            @Override
            protected void warn(BaseDownloadTask task) {
            }
        }).start();

    }
}